// pages/checkout/index.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    data: [],
    loading: 0,
    address: {},
    use_yie: 0,
    shop_id: 0,
    payment_type:'',
    card_code: '',
    order_amount: 0,
    multiArray: [],
    user_info: {},
    table_id:0,
  },
  switch1Change: function (e) {
    if (this.data.user_info.store_member.money > this.data.data.total_price) {
      var use_yie = e.detail.value ? 1 : 0;
      this.setData({ use_yie: use_yie });
      this.setOrderAmount();
    } else {
      app.alert("余额不足，请先充值!");
      this.setData({ use_yie: 0 });
    }
    // console.log(e.detail.value);
  },
  setOrderAmount: function () {
    if (!this.data.user_info.store_member || !this.data.data.total_price) {
      return;
    }
    var order_amount = 0;
    if (this.data.use_yie == 1) {
      order_amount = this.data.user_info.store_member.money > this.data.data.total_price ? 0 : (this.data.data.total_price - this.data.user_info.store_member.money);
    } else {
      order_amount = this.data.data.total_price;
    }
    order_amount.toFixed(2)
    this.setData({ order_amount: order_amount })
  },
  getInfo: function () {
    var that = this;
    app.api("api/user/info", {
      fields: "avatarUrl,user_id,last_update_time,nickname"
    }, function (res) {

      if (res.code != 200) {
        app.alert(res.msg);
        return;
      }

      that.setData({ user_info: res.data });
      that.setOrderAmount();
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.data.table_id = options.table_id ? options.table_id : 215;
    //this.setData({ shop_id: shop_id});
    this.setData({ extConfig: app.getExtConfigSync() })
    this.getTableInfo();
   
  },

  //桌位信息
  getTableInfo: function () {
    app.api("mall/mall_tables/find", {
      id: this.data.table_id
    }, (res) => {
      if (res.code != 200) {
        app.alert(res.msg);
      }
      this.setData({ tableInfo: res.data, shop_info: res.data.shop, shop_id: res.data.shop.id });
      this.getInfo();
      this.loadCart();
      
    })
  },
  //加载购物车
  loadCart(reload = 0) {
    var that = this;
    if (reload == 1) {
      this.setData({
        loading: 0,
        listData: [],
      });
    }
    this.data.loading = 1;
    app.api("mall/cart/getcartByUserId", {
      shop_id: this.data.shop_id,
      card_code: this.data.card_code,
      table_id: this.data.table_id,
    }, function (res) {
      that.data.loading = 0;
      if (res.code != 200) {
        app.alert(res.msg);
        return;
      }
      if (res.data.cardRes && res.data.cardRes.code > 0) {
        app.alert(res.data.cardRes.msg);
        that.data.card_code = "";
      }
      that.setData({
        data: res.data,
      });

      that.setOrderAmount();
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var reload = app.getPageData("checkout/index", 'reload');
    var card_code = app.getPageData("card/index", 'card_code');
    if (reload == 1) {
      app.setPageData("checkout/index", { reload: 0 });
      this.loadCart(1);
    }
    if (card_code) {
      app.setPageData("card/index", { card_code: 0, card_id: 0 });
      this.data.card_code = card_code;
      this.loadCart(1);
    }

  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  suc: function () {
    app.setPageData("bookOffline/pages/index",{reload:1});
    wx.navigateTo({
      url: '/bookOffline/pages/order',
    })
  },

  formSubmit(e){
    // { { user_info.store_member && user_info.store_member.money > 0 } }
    var that = this;
    // //微信支付
    // if (Number(this.data.user_info.store_member.money) < this.data.order_amount) {
    //   that.data.use_yie = 0;
    //   that.postPay(e);
    //   return;
    // }
    //选择微信还是余额
    var itemListArray = [];
    //可使用余额支付
    if (Number(this.data.user_info.store_member.money) > this.data.order_amount){
      itemListArray.push({
        text: '余额支付', act: function () {
          that.data.use_yie = 1;
          that.postPay(e);
        }
      });

    }
   //微信支付 
    itemListArray.push({
      text: '微信支付', act: function () {
        that.data.use_yie = 0;
        that.postPay(e);
      }
    });
//当面付款
    // itemListArray.push({
    //   text: '线下支付', act: function () {
    //     that.data.use_yie = 0;
    //     that.data.payment_type = 'offline_payment';
    //     that.postPay(e);
    //   }
    // });

    var itemList = [];
    //console.log(itemListArray);
    for (var i in itemListArray) {
      itemList.push(itemListArray[i].text);
    }
    wx.showActionSheet({
      itemList: itemList,
      success: function (res) {
        console.log(itemListArray[res.tapIndex]);
        itemListArray[res.tapIndex]['act']();
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },
  //生成订单
  postPay: function (e) {
    console.log(e);
    var post = e.detail.value;
    var formId = e.detail.formId;
    var that = this;
    that.setData({ loading: 1, disabled: 1 });
    that.data.payloading = 1;
  
    app.api("api/pay/bookOffline", {
      remark: post.remark,
      formId: formId,
      payment_type: this.data.payment_type,
      table_id: this.data.table_id,
      shop_id: this.data.shop_id,
      use_yie: this.data.use_yie,
      card_code: this.data.card_code,
      table_id: this.data.table_id,
    }, function (res) {
      if (res.code != 200) {
        app.alert(res.msg);
        that.data.payloading = 0;
        that.setData({ 'loading': 0 });
        that.setData({ 'disabled': 0 });
        return false;
      }
      var order_sn = res.data.order_sn;
      app.api("api/pay/topay", {
        order_sn: order_sn
      }, function (res) {
        if (res.data && res.data.error_code == "1001") {
          that.data.card_code = "";
        }
        if (res.code != 200) {
          app.alert(res.msg);
          that.data.payloading = 0;
          that.setData({ 'loading': 0 });
          that.setData({ 'disabled': 0 });
          return false;
        }

        if (res.data.over == 1) {
          that.suc();
          return;
        }
        var params = res.data;
        //params.total_fee = 0.1;
        params.success = function (res) {
          that.setData({ loading: 0, disabled: 0 });
          that.suc();
        }
        params.fail = function (res) {
          if (res.errMsg == 'requestPayment:fail cancel') {
            that.setData({ loading: 0, disabled: 0 });
            wx.navigateTo({
              url: '/bookOffline/pages/order_detail?order_sn=' + order_sn,
            })
            return false;
          }
          app.alert(res.errMsg);
        }
        console.log(params);
        wx.requestPayment(params)
      })
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.loadCart(1);
    wx.stopPullDownRefresh();
  },

  moreAct: function (e) {
    var that = this;
    var itemListArray = [];
    var goods_id = e.currentTarget.dataset.goods_id;
    var goods_spec_id = e.currentTarget.dataset.goods_spec_id;
    itemListArray.push({
      text: '删除此商品', act: function () {
        app.api("mall/cart/add", {
          goods_id: goods_id,
          goods_spec_id: goods_spec_id,
          table_id: that.data.table_id,
          count: 0,
        }, function (res) {
          if (res.code != 200) {
            app.alert(res.msg);
            return;
          }
          that.loadCart(1);
        })
      }
    });
    itemListArray.push({
      text: '返回', act: function () {
        wx.navigateBack()
      }
    });
    var itemList = [];
    //console.log(itemListArray);
    for (var i in itemListArray) {
      itemList.push(itemListArray[i].text);
    }
    wx.showActionSheet({
      itemList: itemList,
      success: function (res) {
        console.log(itemListArray[res.tapIndex]);
        itemListArray[res.tapIndex]['act']();
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})